package com.shop.daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.shop.dao.BaseDao;

/**
 * 
 * <b>dao层基础操作类<b>
 * @author 威 
 * <br>2017年12月 
 * 
 * @param <T>
 */
public class BaseDaoImpl<T> implements BaseDao<T> {

	@Resource
	private SessionFactory sessionFactory ;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		return sessionFactory.openSession() ;
	}
	
	public Session getCurrentSession(){
		return sessionFactory.getCurrentSession() ;
	}
	
	private Class<?> cls ;
	public BaseDaoImpl(Class<?> cls){
		this.cls = cls ;
	}
	
	@Override
	public boolean save(T t) {
		Session session = getSession() ;
		System.out.println(cls.getName() + ":save") ;
		System.out.println(cls.getName() + ":" + sessionFactory) ;
		session.save(t) ;
		return true ;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll(String className) {
		System.out.println(cls.getName() + ":" + "查找所有") ;
		Query query = getSession().createQuery("from " + className) ;
		List<T> list = query.list() ;
		return list ;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T findById(Integer id) {
		Session session = getSession() ;
		return (T) session.get(cls, id) ;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean delete(Integer id) {
		Session session = getSession() ;
		T t = (T) session.get(cls, id) ;
		session.delete(t) ;
		session.beginTransaction().commit() ;
		return true ;
	}
	
}
